import Enumerable from 'linq';
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import * as UUID from '@/utils/uuid';
import { toWords } from '@/utils/engWords';
import AccountJS from '@/utils/account';

import { Row, Col, Icon, Form, Button, Avatar, InputNumber, Popconfirm, Modal, Select, Input, Divider } from 'antd';

import styles from './styles.less';
import { Spin } from 'antd';

const FormItem = Form.Item;
const { Option } = Select;


function toItemDesc(list, type) {
  if (list.length <= 0) return null;
  var groupSum = Enumerable.from(list).distinct(r => r.objectNumber).groupBy("$.boxTypeName", null,
    function (key, g) {
      var result = {
        boxType: key,
        count: g.count(),
        total: g.sum("$.qty")
      }
      return result;
    }).toArray();

  var str = '';
  var total = 0;
  groupSum.map(item => {
    str += item.count + '*' + item.boxType + '+';
    total += item.count;
  })

  var strSimple = toWords(total) + '(' + str.slice(0, str.length - 1) + ')';
  var strFull = toWords(total) + '(' + str.slice(0, str.length - 1) + ') container(s) only';
  return (type === "simple" ? strSimple : strFull).toUpperCase();
}


const ModelName = "box";

@connect(({ loading, pom, boxType }) => ({
  loading: loading.models[ModelName],
  poms: pom.list,
  boxTypes: boxType.list,
}))
@Form.create()
class Comp extends PureComponent {
  bill = undefined;

  state = {
    list: [],
    canEditBox: false,
  }

  constructor(props) {
    super(props);

    const { getInstance } = props;
    if (typeof getInstance === 'function') {
      getInstance(this);
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.bill !== this.props.bill) {
      const { dispatch } = this.props;
      if (nextProps.bill && nextProps.bill.id > 0) {

        dispatch({
          type: `box/getByBillId`,
          payload: nextProps.bill.id,
          callback: (resp) => {
            this.setState({ list: resp }, () => {
              this.setState({
                canEditBox: nextProps.bill.mblId > 0 || !nextProps.bill.isHasHBL
              })
            });
          }
        })

      }
    }
  }

  remove = (item) => {
    const v2 = this.state.list.filter(r => r.id !== item.id);
    this.setState({ list: v2 });
  }

  addItem = () => {
    const { poms } = this.props;
    var preItem = this.state.list[0];
    var preBoxType = 0;
    if (preItem) {
      preBoxType = preItem.boxTypeId;
    }

    this.setState({
      list: [
        ...this.state.list,
        {
          id: UUID.uuid2(),
          boxTypeId: preBoxType,
          qtyPOM: poms.find(r => r.pomType === 1).id,
          weightPOM: poms.find(r => r.pomType === 2).id,
          measurePOM: poms.find(r => r.pomType === 3).id
        }]
    });
  }

  render() {
    const { form: { getFieldDecorator }, poms, boxTypes, loading } = this.props;
    const { list, canEditBox } = this.state;

    const formLayout = {
      labelCol: {
        xs: { span: 0 },
        sm: { span: 0 },
        lg: { span: 0 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 24 },
        lg: { span: 24 },
      },
    };

    const footer = () => {
      if (list && list.length > 0) {

        const groupSum_qty = AccountJS.format(Enumerable.from(list).sum(r => r.qty), 2);
        const groupSum_weight = AccountJS.format(Enumerable.from(list).sum(r => r.weight), 2);
        const groupSum_measure = AccountJS.format(Enumerable.from(list).sum(r => r.measure), 2);

        return (
          <div className={styles.summaryRow} >
            <Row>
              <Col span={12}>
                {toItemDesc(list)}
              </Col>
              <Col span={4} style={{ textAlign: 'right' }}>{groupSum_qty}</Col>
              <Col span={4} style={{ textAlign: 'right' }}>{groupSum_weight}</Col>
              <Col span={3} style={{ textAlign: 'right' }}>{groupSum_measure}</Col>
            </Row>

          </div >
        );
      }
      else {
        return '';
      }
    }

    return (<div className={styles.container} >
      <Spin spinning={loading}>
        <Form>
          <Row gutter={1} className={styles.titleRow}>
            <Col span={1} className={styles.leaderCol} style={{ width: '2em' }}>
              <Icon
                className={styles.dynamic_button}
                style={{ display: canEditBox ? '' : 'none' }}
                type="plus"
                onClick={e => { e.preventDefault(); this.addItem(); }}
              />
            </Col>
            <Col span={2} className={styles.labelCol}>柜型</Col>
            <Col span={5} className={styles.labelCol}>货柜号</Col>
            <Col span={5} className={styles.labelCol}>封条号</Col>
            <Col span={4} className={styles.labelCol}>数量</Col>
            <Col span={4} className={styles.labelCol}>重量</Col>
            <Col span={3} className={styles.labelCol}>体积</Col>
          </Row>

          <div className={styles.dataRow}>
            {
              list && list.map((item, index) => {
                return <Row gutter={1} key={item.id}  >
                  <Col span={1} className={styles.leaderCol} style={{ width: '2em' }}>
                    <Icon
                      className={styles.dynamic_button}
                      style={{ marginTop: '1em', display: canEditBox ? '' : 'none' }}
                      type="minus"
                      onClick={() => this.remove(item)}
                    />
                  </Col>
                  <Col span={2} className={styles.labelCol}>
                    <FormItem {...formLayout} hasFeedback={false} >
                      {getFieldDecorator(`boxType_${index}`, {
                        rules: [{ required: true }],
                        initialValue: item ? item.boxTypeId : 0,
                      })(
                        <Select size="small"
                          showSearch
                          optionFilterProp="children"
                          filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}>
                          {boxTypes.map(item => <Option key={item.id} value={item.id}>{item.objectName}</Option>)}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col span={5} className={styles.labelCol}>
                    <FormItem {...formLayout}>
                      {getFieldDecorator(`objectNumber_${index}`, {
                        rules: [{ required: true, message: '请输入货柜号' }],
                        initialValue: item.objectNumber,
                      })(<Input size="small" />)}
                    </FormItem>
                  </Col>
                  <Col span={5} className={styles.labelCol}>
                    <FormItem {...formLayout} >
                      {getFieldDecorator(`sealNumber_${index}`, {
                        rules: [{ required: true, message: '请输入封条号' }],
                        initialValue: item.sealNumber,
                      })(<Input size="small" />)}
                    </FormItem>
                  </Col>
                  <Col span={4} className={styles.labelCol} >
                    <div style={{ display: 'flex' }}>
                      <FormItem {...formLayout} hasFeedback={false} >
                        {getFieldDecorator(`qty_${index}`, {
                          rules: [{ required: true }],
                          initialValue: item.qty,
                        })(<InputNumber style={{ width: '100%' }} size="small" />)}
                      </FormItem>
                      <FormItem {...formLayout} hasFeedback={false} >
                        {getFieldDecorator(`qtyPom_${index}`, {
                          rules: [{ required: true }],
                          initialValue: item ? item.qtyPOM : 0,
                        })(
                          <Select size="small"
                            style={{ flex: 'auto', minWidth: '100px', width: 'auto' }}
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} >
                            {poms.filter(item => item.pomType === 1).map(item => <Option key={item.id} value={item.id}>{item.objectName}</Option>)}
                          </Select>
                        )}
                      </FormItem>
                    </div>
                  </Col>
                  <Col span={4} className={styles.labelCol} >
                    <div style={{ display: 'flex' }}>
                      <FormItem {...formLayout} hasFeedback={false} >
                        {getFieldDecorator(`weight_${index}`, {
                          rules: [{ required: true }],
                          initialValue: item.weight,
                        })(<InputNumber size="small" style={{ width: '80%' }} />)}
                      </FormItem>
                      <FormItem {...formLayout} hasFeedback={false} >
                        {getFieldDecorator(`weightPom_${index}`, {
                          rules: [{ required: true }],
                          initialValue: item ? item.weightPOM : 0,
                        })(
                          <Select size="small"
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} style={{ flex: 'auto' }}>
                            {poms.filter(item => item.pomType === 2).map(item => <Option key={item.id} value={item.id}>{item.objectName}</Option>)}
                          </Select>
                        )}
                      </FormItem>
                    </div>
                  </Col>
                  <Col span={3} className={styles.labelCol} >
                    <div style={{ display: 'flex' }}>
                      <FormItem {...formLayout} hasFeedback={false} >
                        {getFieldDecorator(`measure_${index}`, {
                          rules: [{ required: true }],
                          initialValue: item.measure,
                        })(<InputNumber style={{ width: '100%' }} size="small" />)}
                      </FormItem>
                      <FormItem {...formLayout} hasFeedback={false} >
                        {getFieldDecorator(`measurePom_${index}`, {
                          rules: [{ required: true }],
                          initialValue: item ? item.measurePOM : 0,
                        })(
                          <Select size="small"
                            showSearch
                            optionFilterProp="children"
                            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0} style={{ flex: 'auto' }}>
                            {poms.filter(item => item.pomType === 3).map(item => <Option key={item.id} value={item.id}>{item.objectName}</Option>)}
                          </Select>
                        )}
                      </FormItem>
                    </div>
                  </Col>
                </Row>
              })}
          </div>
          {footer()}
        </Form></Spin></div>
    );

  }
}

export default Comp;

